package com.lbg.drug.service.impl;

import com.lbg.drug.commont.untils.PageUtils;
import com.lbg.drug.dto.Admindto;
import com.lbg.drug.dto.StoreDto;
import com.lbg.drug.dto.StorePage;
import com.lbg.drug.entity.Admin;
import com.lbg.drug.entity.DrugFacts;
import com.lbg.drug.entity.Stock;
import com.lbg.drug.entity.Store;
import com.lbg.drug.mapper.AdminMapper;
import com.lbg.drug.mapper.DrugFactsMapper;
import com.lbg.drug.mapper.StockMapper;
import com.lbg.drug.mapper.StoreMapper;
import com.lbg.drug.service.StoreService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cglib.beans.BeanCopier;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpSession;
import java.util.Date;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author lbg
 * @since 2022-04-29
 */
@Service
public class  StoreServiceImpl implements StoreService {



    @Autowired
    private StoreMapper storeMapper;

    @Autowired
    private AdminMapper adminMapper;

    @Autowired
    private StockMapper stockMapper;

    @Autowired
    private DrugFactsMapper drugFactsMapper;


    @Override
    public String add(StoreDto storeDto, HttpSession session) {
        Store store = new Store();
        BeanCopier.create(StoreDto.class, Store.class, false).copy(storeDto, store, null);
        store.setStoreTime(new Date());
        Admindto admin = (Admindto) session.getAttribute("Admin");
        Admin admin1 = adminMapper.selectById(admin.getUserId());
        store.setUserName(admin1.getUserName());
        Stock stock = new Stock();
        stock.setDrugId(storeDto.getDrugId());
        stock.setDrugAmount(storeDto.getStoreAmount());
        stock.setUpdateTime(new Date());
        DrugFacts drugFacts = drugFactsMapper.selectById(storeDto.getDrugId());
        stock.setGlobalValue(drugFacts.getDrugUnitPrice()*storeDto.getStoreAmount());
        stockMapper.insert(stock);

        storeMapper.insert(store);

        return store.getId();


    }

    @Override
    public PageUtils getALl(StorePage storePage) {
        storePage.setCurrIndex((storePage.getPageNo() - 1) * storePage.getPageSize());
        storePage.setEndIndex(storePage.getPageSize());

        PageUtils pageUtils = new PageUtils(storeMapper.getAllById(storePage), storeMapper.getCount(storePage));

        return pageUtils;
    }

    @Override
    public void de(String id) {
        storeMapper.deleteById(id);
    }

    @Override
    public void up(Store store) {
        storeMapper.updateById(store);

    }
}
